/**
 * 常用方法封装 请求，文件上传等
 * @author echo. 
 **/
// import store from '@/store'
import validate from "@/common/test";
const tui = {
	//接口地址
	interfaceUrl: function() {
		return 'https://yeb.byjx.shop/api'
		// return 'https://yc.upyckj.cn/api'
	},
	toast: function(text, duration, success) {
		uni.showToast({
			title: text || "出错啦~",
			icon: success ? 'success' : 'none',
			duration: duration || 2000
		})
	},
	modal: function(title, content, showCancel, callback, confirmColor, confirmText) {
		return new Promise((resolve, reject) => {
			uni.showModal({
				title: title || '提示',
				content: content,
				showCancel: showCancel,
				cancelColor: "#555",
				confirmColor: confirmColor || "#5677fc",
				confirmText: confirmText || "去登陆",
				success(res) {
					if (res.confirm) {
						resolve(res)
					} else {
						reject(res)
					}
				}
			})

		})
	},

	isAndroid: function() {
		const res = uni.getSystemInfoSync();
		return res.platform.toLocaleLowerCase() == "android"
	},
	isPhoneX: function() {
		const res = uni.getSystemInfoSync();
		let iphonex = false;
		let models = ['iphonex', 'iphonexr', 'iphonexsmax', 'iphone11', 'iphone11pro', 'iphone11promax']
		const model = res.model.replace(/\s/g, "").toLowerCase()
		if (models.includes(model)) {
			iphonex = true;
		}
		return iphonex;
	},
	constNum: function() {
		let time = 0;
		// #ifdef APP-PLUS
		time = this.isAndroid() ? 300 : 0;
		// #endif
		return time
	},
	delayed: null,
	/**
	 * 请求数据处理
	 * @param string url 请求地址
	 * @param string method 请求方式
	 *  GET or POST
	 * @param {*} postData 请求参数
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool isForm 数据格式
	 *  true: 'application/x-www-form-urlencoded'
	 *  false:'application/json'
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 */
	get(url, postData, hideLoading, isDelay, isForm) {
		return this.request(url, postData, "GET", hideLoading, isDelay, isForm)
	},
	post(url, postData, hideLoading, isDelay, isForm) {
		return this.request(url, postData, "POST", hideLoading, isDelay, isForm)
	},
	request: function(url, postData, method, hideLoading, isDelay, isForm) {
		//接口请求
		let baseUrl = tui.interfaceUrl()

		let urls = validate.url(url) ? url : (baseUrl + (url
			.indexOf('/') == 0 ?
			url : '/' + url));

		let loadding = false;
		tui.delayed && uni.hideLoading();
		clearTimeout(tui.delayed);
		tui.delayed = null;
		if (!hideLoading) {
			tui.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: '加载中...',
					success(res) {
						loadding = true
					}
				})
			}, isDelay ? 1000 : 0)
		}



		return new Promise((resolve, reject) => {
			console.log('token',uni.getStorageSync('token'))
			uni.request({
				url: urls,
				data: postData,
				header: {
					'Authorization':uni.getStorageSync('token'),
					'app-id': 'wx3443d84f50aff24b',
					'client-type': 'MA-WX',
					'Content-Type': 'application/json' ,
					'third-session':  uni.getStorageSync('token')
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					clearTimeout(tui.delayed);
					tui.delayed = null;
					if (loadding && !hideLoading) {
						uni.hideLoading()
					}
					// 全局请求code 判断
					if (res.data && res.data.code == 401) {
						// token失效就跳转登录重新登录获取新的token
						uni.clearStorageSync();
						uni.navigateTo({
							url: '/pages/login/login'
						})
						// tui.modal('提示', '请先登录', false,).then((res) => {
						// 	uni.navigateTo({
						// 		url: '/pages/login/login'
						// 	})

						// })
						return
					} 
					if(res.data.code == 500) {
						tui.toast(res.data.msg)
					}
					resolve(res)
				},
				fail: (res) => {
					clearTimeout(tui.delayed)
					tui.delayed = null;
					tui.toast("网络不给力，请稍后再试~")
					reject(res)
				}
			})
		})
	},
	/**
	 * 上传文件
	 * @param string url 请求地址
	 * @param string src 文件路径
	 */
	uploadFile: function(url, src) {
		
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: tui.interfaceUrl() + url,
				filePath: src,
				name: 'file',
				header: {
					'app-id': 'wx3443d84f50aff24b',
					'client-type': 'MA-WX',
					'Content-Type': 'application/json' ,
					'third-session':  uni.getStorageSync('token'),
					'Authorization':uni.getStorageSync('token'),
				},
				formData: {
					type:'file',
					fileType:'file',
					file:src
				},
				success: function(res) {
					let d = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
					resolve(d)
					
				},
				fail: function(res) {
					reject(res)
					tui.toast(res.msg);
				}
			})
		})
	},
	tuiJsonp: function(url, callback, callbackname) {
		// #ifdef H5
		window[callbackname] = callback;
		let tuiScript = document.createElement("script");
		tuiScript.src = url;
		tuiScript.type = "text/javascript";
		document.head.appendChild(tuiScript);
		document.head.removeChild(tuiScript);
		// #endif 
	},
	//设置用户信息
	setUserInfo: function(mobile, token) {
		//uni.setStorageSync("thorui_token", token)
		uni.setStorageSync("thorui_mobile", mobile)
	},
	//获取token
	getToken() {
		return uni.getStorageSync('token');
		// return store.state.token
	},
	//判断是否登录
	isLogin: function() {
		return uni.getStorageSync("thorui_mobile") ? true : false
	},
	//跳转页面，校验登录状态
	href(url, isVerify) {
		if (isVerify && !tui.isLogin()) {
			uni.navigateTo({
				url: '/pages/common/login/login'
			})
		} else {
			uni.navigateTo({
				url: url
			});
		}
	},
	// 查询版本信息
	queryVersion() {
		this.get('mobile/getConfig').then((res) => {
			// console.log(res, 'req');
		})
	}
}

export default tui